package com.jiazaibendi.lottery.controller;

import com.jiazaibendi.lottery.common.CommonResponse;
import com.jiazaibendi.lottery.common.CommonResponseEnum;
import com.jiazaibendi.lottery.common.SignUtil;
import com.jiazaibendi.lottery.dao.domain.UserInfo;
import com.jiazaibendi.lottery.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zy
 * @Date: 2021/8/9 18:33
 */
@CrossOrigin
@Controller
@RequestMapping("/open")
public class OpenController {

    @Autowired
    private WxService wxService;

    private final String url = "http://www.jiazaibendi.com/cj/index.html?";

    @GetMapping("/verify_wx_token")
    @ResponseBody
    public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("----------------验证微信服务号信息开始----------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
//            System.out.println("----验证服务号结束.........");
            return echostr;
        }else{
            return null;
        }
    }

    //获取code
    @GetMapping("/getOpenId")
    public String getOpenId(@RequestParam(name = "code")String code){
        UserInfo userInfo = wxService.getOpenId(code);
        String returnUrl = "redirect:" + url + "userId=" + userInfo.getId() + "&openId="+userInfo.getOpenid();
        return returnUrl;
    }
}
